package com.cty.util.config;

import com.cty.util.util.CustomThreadPoolTaskExecutor;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类
 *
 * @author : cty
 * @since 2023/11/19
 */

@Configuration
public class ThreadPoolConfiguration {

    /**
     * 核心线程数 = 可用处理器数量 * 2
     */
    private static final Integer CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
    /**
     * 最大线程数
     */
    private static final Integer MAX_POOL_SIZE = 100;
    /**
     * 非核心线程回收等待空闲时间（秒）
     */
    private static final Integer KEEP_ALIVE_SECONDS = 60;
    /**
     * 等待队列大小
     */
    private static final Integer QUEUE_CAPACITY = 1000;

    /**
     * customThreadPoolTaskExecutor
     *
     * 拒绝处理策略
     * CallerRunsPolicy()：交由调用方线程运行，比如 main 线程
     * AbortPolicy()：直接抛出异常
     * DiscardPolicy()：直接丢弃
     * DiscardOldestPolicy()：丢弃队列中最老的任务
     */
    @Bean
    public CustomThreadPoolTaskExecutor customThreadPoolTaskExecutor() {
        CustomThreadPoolTaskExecutor threadPoolExecutor =   new CustomThreadPoolTaskExecutor();
        threadPoolExecutor.initialize();
        threadPoolExecutor.setCorePoolSize(CORE_POOL_SIZE);
        threadPoolExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        threadPoolExecutor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        threadPoolExecutor.setQueueCapacity(QUEUE_CAPACITY);
        threadPoolExecutor.setThreadFactory(new ThreadFactoryBuilder().setNameFormat("common-threadpool-%d").build());
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolExecutor;
    }
}
